package com.lrl.service;

import com.lrl.mapper.AdminMapper;
import com.lrl.pojo.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    AdminMapper adminMapper;

    @Override
    public List<Admin> getAdminsList() {
        return adminMapper.getAllAdmins();
    }

    @Override
    public Admin getAdminByName(String name) {
        return adminMapper.queryAdminByName(name);
    }

    @Override
    public String getPwdByName(String name) {
        return adminMapper.queryPasswordByName(name);
    }

    @Override
    public boolean updateLoginTimeByName(String name) {
        Map<String, Object> map = new HashMap<>();
        map.put("account", name);
        map.put("birth", new Date());

        return adminMapper.updateTimeByName(map) > 0;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        System.out.println(username);//输出前台传递进来的管理员名字
        Admin admin = adminMapper.queryAdminByName(username);
//        System.out.println(admin);//输出查找到的管理员
        if (admin == null) {
            throw new UsernameNotFoundException("该管理员不存在");
        }

        //用于添加用户的权限。只要把用户权限添加到authorities 就万事大吉。
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();//建立List是为了日后的多种权限做准备的
        authorities.add(new SimpleGrantedAuthority(admin.getRole()));
//        System.out.println(admin.getRole());//输出权限名
        return new org.springframework.security.core.userdetails.User(admin.getAccount(),
                admin.getPassword(), authorities);
    }
}
